package com.qf.service.Impl;


import com.qf.bean.CartBean;
import com.qf.dao.CartDao;
import com.qf.dao.Impl.CartDaoImpl;
import com.qf.pojo.Cart;
import com.qf.pojo.Product;
import com.qf.pojo.User;
import com.qf.service.CartService;
import com.qf.service.ProductService;
import com.qf.util.DBUtils;

import javax.servlet.http.HttpSession;
import java.sql.Connection;
import java.util.Date;
import java.util.List;


public class CartServiceImpl implements CartService {

    //商品对象
    private ProductService productService = new ProductServiceImpl();

    //购物车
    private CartDao cartDao = new CartDaoImpl();

    @Override
    public void add(String pid, String amount, HttpSession session) {

        Connection connection = DBUtils.getConnection();

        try {
            connection.setAutoCommit(false);//开启事务

            //保存数据到购物车表
            //要获取的数据：用户的id -> session中取，价格 -> 商品中取，商品 -> 通过传过来的商品id查询数据库
            User user = (User)session.getAttribute("user");
            Integer uid = user.getUid();

            //获取商品对象
            Product product = productService.findById(pid);

            //创建购物车对象
            Cart cart = new Cart();
            cart.setUid(uid);
            cart.setPid(Integer.parseInt(pid));
            cart.setPrice(product.getPrice());//单价
            cart.setNum(Integer.parseInt(amount));
            cart.setCreated_user(user.getUsername());
            cart.setCreated_time(new Date());//当前时间
            cart.setModified_user(user.getUsername());
            cart.setModified_time(new Date());
            cart.setStatus(0);

            //保存数据到购物车
            cartDao.insert(cart);


        }catch (Exception e){

            try {
                connection.rollback();//回滚事务
            } catch (Exception e1) {
                e1.printStackTrace();
            }

        }finally {
            try {
                connection.commit();//提交事务
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public List<CartBean> findAll(Integer uid) {
        return cartDao.findAll(uid);
    }
}
